package com.demo.demo.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 懒汉模式
 */
public class Lazy {
    private volatile static Lazy lazy;

    private Boolean qi=false;
    private Lazy(){
        synchronized (Lazy.class){
            if (!qi){
                qi=true;
            }else{
                throw  new RuntimeException("反射!");
            }
        }
        System.out.println(Thread.currentThread().getName());
    }

    public static Lazy getInstance(){

        if(lazy==null){
            synchronized (Lazy.class){
                if (lazy==null){
                    lazy = new Lazy();//不是原子性操作
                    /**
                     * 1、分配内存空间
                     * 2、执行构造方法，初始化对象
                     * 3、把对象指向这个空间
                     *
                     * 123
                     * 132
                     * 指令重排
                     */
                }
            }
        }
        return lazy;
    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

        /*for (int i = 0; i <10 ; i++) {
            new Thread(()->{
                Lazy.getInstance();
            }).start();
        }*/

        //反射
        Constructor<Lazy> constructor = Lazy.class.getDeclaredConstructor(null);
        constructor.setAccessible(true);

        Lazy lay=constructor.newInstance();
        Lazy lazy=constructor.newInstance();
        System.out.println(lay);
        System.out.println(lazy);
    }
}
